<?php
namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Request;

class Admin extends Controller
{
    public function _initialize()
    {
        if (!is_login()) {
            $this->error('请先登录', 'login/index');
        }
        $data['_USER_INFO_'] = Db::name('Admin')->where('id', is_login())->field('id,admin_username,admin_email,admin_realname,admin_tel')->find();
        $menus = $this->getMenu();
        $data['controller_name'] = Request::instance()->controller();
        $data['action_name'] = Request::instance()->action();
        $data['__MENU__'] = $this->checkAuthMenus($menus, $data['controller_name'], $data['action_name']);
        $this->assign($data);
    }

    /*
     * 获取菜单
     * */
    private function getMenu()
    {
        $m = Db::name('AuthRule');
        $field = 'id,name,title,css,pid,is_show';
        $list = $m->field($field)->where('status=1')->select();
        return $list;
    }

    /*
     * 返回用户有权限菜单
     * */
    private function checkAuthMenus($list, $controller, $action)
    {
        $uid = is_login();
        $group = Db::name('AuthGroupAccess')->where('uid', $uid)->value('group_id');
        $roles = Db::name('AuthGroup')->where('id', $group)->where('status', 1)->value('rules');
        if (empty($roles)&&$group!=1) {
            return array();
        }
        $arr_role = explode(',', $roles);
        $flag = false;
        foreach ($list as $key => &$val) {
            //删除不显示的
            if (!$val['is_show']) {
                unset($list[$key]);
            }
            //超级管理员不检测
            if($group!==1){
                $arr = explode('/', $val['name']);
                $arr[0]=isset($arr[0])?$arr[0]:'';
                $arr[1]=isset($arr[1])?$arr[1]:'';
                if (strtolower($controller) === strtolower($arr[0]) && strtolower($action) === strtolower($arr[1])) {
                    if (in_array($val['id'], $arr_role)) {
                        $flag = true;
                    }
                }
                if (!in_array($val['id'], $arr_role)) {
                    unset($list[$key]);
                }
            }

        }
        //超级管理员
        if ($group == 1) {
            $flag = true;
        }
        if (!$flag) {
            $this->error('您没有权限,请联系管理员');
        }
        //转化成树形
        $list = list_to_tree($list);
        return $list;
    }

    /*
     * 设置状态
     * @param $table 表名
     * @param $filed 字段
     * @param $id    主键id
     * */
    protected function setStatus($table, $filed, $id)
    {

    }
}
